﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EDiamondModel;

public partial class Admin_SanPhamThem : System.Web.UI.Page
{
    EDiamondEntities1 db = new EDiamondEntities1();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            XuatMaLoai();
        }
    }

    protected void lbtnGhiNhanSanPham_Click(object sender, EventArgs e)
    {
        string tensanpham = txtTenSanPham.Text.Trim();
        int dongia = int.Parse(txtDonGia.Text);
        int khuyenmai = int.Parse(txtKhuyenMai.Text);
        string mota = txtMoTa.Text;
        double trongluong = double.Parse(txtTrongLuong.Text.Trim());

        int s = db.SanPhams.Count(p => p.TenSanPham == tensanpham);//Kiểm tra duy nhất
        if (s == 0) //Thêm
        {
            SanPham sp = new SanPham();
            sp.TenSanPham = tensanpham;
            sp.DonGia = dongia;
            sp.KhuyenMai = khuyenmai;
            sp.MoTa = mota;
            if (FileUpload1.HasFile) sp.Hinh =  FileUpload1.FileName;
            sp.TrongLuong = trongluong;
            sp.NgayCapNhat = DateTime.Now;
            sp.MaLoai = Convert.ToInt32(ddlMaLoai.SelectedValue);
            sp.NgungBan = false;
            sp.BiDanh = Thuvien.BoDauTiengViet(sp.TenSanPham);

            db.SanPhams.AddObject(sp);
            db.SaveChanges();

            if (FileUpload1.HasFile)
            {
                string f = "~/Photos/SanPham/" + sp.Hinh;
                FileUpload1.SaveAs(Server.MapPath(f));
                
            }
            Response.Redirect("~/Admin/SanPham.aspx");


        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "redirectMe", "alert ('Tên sản phẩm đã có rồi!');", true);
            txtTenSanPham.Focus();
        }
    }
    void XuatMaLoai()
    {
        ddlMaLoai.DataValueField = "MaLoai";
        ddlMaLoai.DataTextField = "TenLoai";
        ddlMaLoai.DataSource = db.LoaiSanPhams;
        ddlMaLoai.DataBind();
    }
}